<template>

  <!-- 广告组的数据概览-->
  <div style="margin-bottom: 48px;">

    <el-card style="margin-bottom: 24px;" shadow="never">
      <group-bid-header />
    </el-card>

    <!-- 核心指标开始 -->

    <el-card
      v-loading="targetLoading"
      class="box-card"
      style="margin-bottom: 24px;"
      :element-loading-text="loadingText"
      shadow="never"
    >
      <cell-header title="核心指标">
        <!-- <choose-time /> -->
      </cell-header>
      <div class="data">
        <coreTarget :target-data="targetList" :time-arr="[queryData.startTime,queryData.endTime]" :adchannel-type="campaignInfo.adchannelType" />
      </div>
    </el-card>

    <!-- 核心指标结束 -->

    <!-- 趋势对比开始 -->
    <el-card class="trend-card" shadow="hover">

      <div class="trend">
        <cell-header title="趋势对比">
          <!-- <choose-time @ /> -->
        </cell-header>
        <div>
          <el-tabs v-model="tabActiveName">
            <!-- 日期开始 -->
            <el-tab-pane label="日期" name="date">
              <div v-if="tabActiveName=='date'" v-loading="dateLoading" style="width: 100%;" element-loading-text="数据加载中,请稍候">
                <date-echart :date-info="dateEchartList" :adchannel-type="campaignInfo.adchannelType">
                  <div slot="right">
                    <el-radio-group v-model="timeAccuracy" size="small" @change="findReportAdGroupTotal">
                      <el-radio-button label="DAILY">每天</el-radio-button>
                      <el-radio-button label="HOURLY" :disabled="$getDiffDay(queryData.startTime,queryData.endTime)>31">每小时</el-radio-button>
                    </el-radio-group>
                  </div>
                </date-echart>
              </div>

            </el-tab-pane>
            <!-- 日期结束 -->

            <el-tab-pane v-if="campaignInfo.adchannelType!=='DISPLAY'" label="关键词" name="words">
              <div v-if="!allWordList.length&&tabActiveName==='words'" style="color: #909399;font-size: 14px;height: 236px;line-height: 236px;text-align: center;">暂无数据</div>
              <selectEchart
                v-if="tabActiveName==='words'&&allWordList.length"
                v-loading="wordLoading"
                :echart-data="wordEchartsInfo"
                :val-list="wordsVal"
                element-loading-text="数据加载中,请稍候"
                :adchannel-type="campaignInfo.adchannelType"
              >
                <div slot="left" class="left-box flex">
                  <div class="left-box-rt">
                    <template v-for="(item,index) in allWordList">
                      <el-select
                        v-if="index<5"
                        :key="index"
                        v-model="checkedWords[index]"
                        size="small"
                        placeholder="请选择关键词"
                        filterable
                        @change="findReportKeywordTotalBySearch"
                      >
                        <el-option label="不显示" :class="'select'+(index+1)+'-op'">
                          <p>
                            <i class="el-icon-check"></i>
                            <span>不显示</span>
                          </p>
                        </el-option>
                        <el-option
                          v-for="element in allWordList"
                          :key="element.keywordId"
                          :label="element.text"
                          :value="element.keywordId"
                          :class="'select'+(index+1)+'-op'"
                        >
                          <p>
                            <i class="el-icon-check"></i>
                            <span>{{ element.text }}</span>
                          </p>
                        </el-option>
                      </el-select>
                    </template>
                  </div>
                </div>
                <div slot="right">
                  <el-radio-group v-model="wordAccuracy" size="small" @change="findReportKeywordTotalBySearch">
                    <el-radio-button label="DAILY">每天</el-radio-button>
                    <!-- <el-radio-button label="HOURLY">每小时</el-radio-button> -->
                  </el-radio-group>
                </div>
              </selectEchart>
            </el-tab-pane>
            <el-tab-pane label="设备" name="facility">

              <audiencesEchart v-if="tabActiveName==='facility'" :echart-data="equipmentEchartList" :adchannel-type="campaignInfo.adchannelType">
                <div slot="right">
                  <el-button size="small" type="primary">每天</el-button>
                </div>
              </audiencesEchart>

            </el-tab-pane>

            <el-tab-pane label="年龄" name="age">
              <audiencesEchart v-if="tabActiveName==='age'" :echart-data="ageEchartList" :adchannel-type="campaignInfo.adchannelType">
                <div slot="right">
                  <el-button size="small" type="primary">每天</el-button>
                </div>
              </audiencesEchart>

            </el-tab-pane>
            <el-tab-pane label="性别" name="sex">
              <audiencesEchart v-if="tabActiveName==='sex'" :echart-data="sexEchartList" :adchannel-type="campaignInfo.adchannelType">
                <div slot="right">
                  <el-button size="small" type="primary">每天</el-button>
                </div>
              </audiencesEchart>

            </el-tab-pane>

            <el-tab-pane v-if="false" label="位置" name="position" />
          </el-tabs>

        </div>
      </div>
    </el-card>

    <!-- 趋势对比结束 -->

    <!-- 词云开始 -->
    <el-card v-if="campaignInfo.adchannelType==='SEARCH'" class="cloud-card" shadow="never" style="margin-bottom: 24px;">

      <cell-header title="词云">
        <!-- <choose-time @ /> -->
      </cell-header>
      <!-- <cloud-echart /> -->
      <word-cloud ref="wordCloud" :time-arr="timeArr" />
    </el-card>
    <!-- 词云结束-->

    <!-- 广告组表格展示开始 -->
    <el-card v-if="campaignInfo.adchannelType==='SEARCH'" class="box-card" shadow="never" l>

      <div class="table-box">
        <cell-header title="广告组关键词" />
        <!-- {{ campaignInfo }} -->
        <el-tabs v-model="tabActiveTable">
          <el-tab-pane label="关键词" name="keyWords">
            <key-words :time-arr="timeArr" @addKeyWord="keyRef" />
          </el-tab-pane>

          <el-tab-pane label="搜索词" name="searchWords">
            <search-words :time-arr="timeArr" />
          </el-tab-pane>

          <el-tab-pane label="屏蔽词" name="blockWord">
            <negative-word :time-arr="timeArr" />
          </el-tab-pane>

        </el-tabs>

        <div />
      </div>
    </el-card>

    <!-- 广告组表格表格展示结束 -->

  </div>
</template>

<script>
import groupBidHeader from '../components/bid-header/group-bid-header.vue'
import dateEchart from '@/components/charts/dateEchart.vue'
import selectEchart from '@/components/charts/selectEchart.vue'
import audiencesEchart from '@/components/charts/audiencesEchart.vue'
import coreTarget from '../components/coreTarget.vue'

import cellHeader from '@/components/cell-header.vue'
// import keyWords from './components/keyWords.vue'
// import negativeWord from './components/negativeWord.vue'
// import searchWords from './components/searchWords.vue'
// import wordCloud from './components/wordCloud.vue'
import keyWords from '../components/word-box/keyWords.vue'
import negativeWord from '../components/word-box/negativeWord.vue'
import searchWords from '../components/word-box/searchWords.vue'
import wordCloud from '../components//word-box/wordCloud.vue'

import {
  findReportAdGroupTotal,
  findReportKeywordTotalBySearch,
  findKeyordsList,
  findReportAdGroupTotalAudienceType
} from '@/api/overView.js'

export default {
  components: {
    // chooseTime,
    groupBidHeader,
    // chartsTable,
    audiencesEchart,
    /* cloudEchart, */
    dateEchart,
    selectEchart,
    wordCloud,
    cellHeader,
    keyWords,
    negativeWord,
    searchWords,
    coreTarget
    // indexCard

  },
  data() {
    return {
      targetLoading: true,
      loadingText: '数据加载中,请稍候',
      queryData: { // 表格查询参数
        teamId: this.$store.state.team.teamId || '',
        currencyType: this.$store.state.user.unit,

        adGroupId: this.$route.query.adGroupId,
        country: '',
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime, // 时区比UTC时间少几个小时
        prop: 'status', // 选择项
        endTime: '', // 开始时间
        startTime: '', // 结束时间
        name: '', // 查询时的名称  模糊查询
        status: '',
        userId: this.$store.state.user.userInfo.userId,
        campaignId: this.$route.query.campaignId || this.$route.query.campaignid,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        type: 'HOURLY'

      },
      timeArr: [], // 时间变化
      tabActiveName: 'date', // 显示那个具体图表

      /* 日期图表*/
      timeAccuracy: 'DAILY', // 请求图表的时间粒度---日期
      dateLoading: true,
      dateEchartList: [],
      /* 关键词图表 */
      allWordList: [],
      checkedWords: [],
      wordLoading: true,
      wordAccuracy: 'DAILY', // 请求图表的时间粒度---关键词

      /* 设备图表 */
      equipmentEchartList: {}, // /请求图表的时间粒度---设备
      // 年龄图表
      ageEchartList: {},
      // 性别图表
      sexEchartList: {},
      checkedList: [],
      tableData: [],
      tabActiveTable: 'keyWords'
    }
  },

  computed: {
    // 选择的时区
    timeZone() {
      return this.$store.state.user.timeZone
    },
    // 选择的开始时间与结束时间
    timeObj() {
      return this.$store.state.overview.timeObj.overViewTime
    },
    wordsVal() {
      if (this.checkedWords.length) {
        const arr = this.checkedWords.map(item => {
          if (!item) {
            const index = this.allWordList.findIndex(v => {
              return this.checkedWords.indexOf(v.keywordId) === -1
            })
            return {
              ...this.allWordList[index],
              key: this.allWordList[index].keywordId,
              name: this.allWordList[index].text,
              selected: false
            }
          } else {
            const index = this.allWordList.findIndex(v => {
              return item === v.keywordId
            })
            return {
              ...this.allWordList[index],
              key: this.allWordList[index].keywordId,
              name: this.allWordList[index].text,
              selected: true
            }
          }
        })

        return arr
      } else {
        return []
      }
    },

    campaignInfo() {
      const allCa = this.$store.state.overview.allCa
      const index = allCa.findIndex(item => {
        return item.campaignId * 1 === this.$route.query.campaignId * 1
      })
      return allCa[index]
    }
  },

  watch: {
    // 时区变化
    timeZone: {
      deep: true,
      handler: function(newV, oldV) {
        this.queryData.countrySX = this.$store.state.user.timeZone // 时区
        this.queryData.timeZone = this.$store.getters.timeZoneTime
        this.findReportAdGroupTotal(true) // 获取核心指标数据以及日期图表数据
        this.findReportKeywordTotalBySearch()
        this.findKeyordsList() // 获取关键词图表数据
        this.findEchartByAge() // 获取图表数据--年龄
        this.findEchartByIPhoneOrIPad() // 获取图表数据--设备
        this.findEchartBySex() // 获取图表数据--性别
      }
    },
    timeObj: {
      deep: true,
      handler: function(newV, oldV) {
        this.pieckerChange(newV)
      }
    }
  },

  mounted() {
    console.log(this.timeObj, '这是开始时间和家属')
    this.pieckerChange(this.timeObj)
  },

  methods: {
    keyRef() {
      setTimeout(() => {
        this.findKeyordsList()
        this.$refs['wordCloud'].getKeyWordArr()
      }, 3500)
    },
    tableCheckChange(data) {
      this.checkedList = JSON.parse(JSON.stringify(data))
    },
    // 日期设置；

    // 日期发生了变化
    pieckerChange(data) {
      this.timeArr = data
      this.queryData.startTime = data.startTime
      this.queryData.endTime = data.endTime
      if (this.$getDiffDay(this.queryData.startTime, this.queryData.endTime) > 31) {
        this.queryData.type = 'DAILY'
        this.timeAccuracy = 'DAILY'
      }
      this.targetLoading = true
      this.dateLoading = true
      if (!this.$route.query.campaignId && !this.$route.query.campaignid) return false
      this.findReportAdGroupTotal(true) // 获取核心指标数据以及日期图表数据
      this.findReportKeywordTotalBySearch()
      this.findKeyordsList() // 获取关键词图表数据
      this.findEchartByAge() // 获取图表数据--年龄
      this.findEchartByIPhoneOrIPad() // 获取图表数据--设备
      this.findEchartBySex() // 获取图表数据--性别
    },

    // 获取广告组下面的全部关键词
    async findKeyordsList() {
      this.wordLoading = true

      const res = await findKeyordsList({
        ...this.queryData,
        campaignId: this.$route.query.campaignId || this.$route.query.campaignid,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        teamId: this.$store.state.team.teamId || ''
      })
      // console.log(res, '所有关键词')
      if (res.data.code === 20000) {
        if (res.data.data && res.data.data.length) {
          this.allWordList = res.data.data
          const arr = []
          const maxNum = this.allWordList.length > 5 ? 5 : this.allWordList.length
          for (let i = 0; i < maxNum; i++) {
            arr.push(res.data.data[i].keywordId)
          }
          this.checkedWords = arr
          this.findReportKeywordTotalBySearch()
        } else {
          this.wordEchartsInfo = {}
          this.wordLoading = false
        }
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误，请稍候重试')
      }
    },

    // 获取日期图表数据
    async findReportAdGroupTotal(targtLoading) {
      this.dateLoading = true
      const res = await findReportAdGroupTotal({
        ...this.queryData,
        campaignId: this.$route.query.campaignId || this.$route.query.campaignid,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        teamId: this.$store.state.team.teamId || '',
        type: this.timeAccuracy,
        audienceType: 'countryOrRegion', // 写死的数据
        typeValue: '' // 写死的数据
      })

      this.targetLoading = false
      this.dateLoading = false
      if (res.data.code && res.data.code === 20000) {
        this.targetLoading = false
        this.echartLoading = false
        this.targetList = JSON.parse(JSON.stringify(res.data.data))
        this.dateEchartList = JSON.parse(JSON.stringify(res.data.data.result))
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误，请稍候重试')
      }
    },

    // 根据关键词获取图表数据
    async findReportKeywordTotalBySearch() {
      if (!this.allWordList.length) return false
      this.wordLoading = true
      const str = this.wordsVal.map(item => {
        return item.keywordId
      })
      const res = await findReportKeywordTotalBySearch({
        ...this.queryData,
        campaignId: this.$route.query.campaignId || this.$route.query.campaignid,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        teamId: this.$store.state.team.teamId || '',
        type: this.wordAccuracy,
        keywordId: str.join(','),
        adgroupId: this.queryData.adGroupId,
        countrySX: this.$store.state.user.timeZone, // 时区
        timeZone: this.$store.getters.timeZoneTime // 时区比UTC时间少几个小时
      })

      // console.log(res, '关键词图表')
      this.wordLoading = false
      if (res.data.code && res.data.code === 20000) {
        this.wordEchartsInfo = res.data.data
      } else {
        this.$message.closeAll()
        this.$message.error(res.data.message || '服务器错误，请稍候重试')
      }
    },
    // 获取图表数据---设备
    async findEchartByIPhoneOrIPad() {
      this.deviceClassLoading = true
      const obj = {
        ...this.queryData,
        campaignId: this.$route.query.campaignId || this.$route.query.campaignid,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        teamId: this.$store.state.team.teamId || '',
        audienceType: 'deviceClass',
        typeValue: 'IPad,IPhone',
        type: 'DAILY'
      }
      const res = await this.findEchartByAudiences(obj)
      this.deviceClassLoading = false
      if (res.data.code && res.data.code === 20000) {
        this.equipmentEchartList = res.data.data
      } else {
        this.equipmentEchartList = {}
      }
    },
    // 获取图表数据---年龄
    async findEchartByAge() {
      this.ageLoading = true

      const obj = {
        ...this.queryData,
        campaignId: this.$route.query.campaignId || this.$route.query.campaignid,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        teamId: this.$store.state.team.teamId || '',
        audienceType: 'ageRange',
        typeValue: '',
        type: 'DAILY'
      }
      const res = await this.findEchartByAudiences(obj)
      this.ageLoading = false
      if (res.data.code && res.data.code === 20000) {
        const obj = { ...res.data.data
        }
        this.ageEchartList = obj
      } else {
        this.ageEchartList = {}
      }
    },
    // 获取图表数据---性别
    async findEchartBySex() {
      this.sexLoading = true
      const obj = {
        ...this.queryData,
        campaignId: this.$route.query.campaignId || this.$route.query.campaignid,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        teamId: this.$store.state.team.teamId || '',
        audienceType: 'gender',
        typeValue: '',
        type: 'DAILY'
      }
      const res = await this.findEchartByAudiences(obj)
      this.sexLoading = false
      if (res.data.code && res.data.code === 20000) {
        this.sexEchartList = res.data.data
      } else {
        this.sexEchartList = {}
      }
    },

    // 获取图表数据---受众
    async findEchartByAudiences(obj) {
      const res = await findReportAdGroupTotalAudienceType({
        ...this.queryData,
        campaignId: this.$route.query.campaignId || this.$route.query.campaignid,
        orgId: this.$route.query.orgId || '', // 如果是自助投放为空
        uuid: this.$route.query.uuid || '',
        aId: this.$route.query.aId || this.$route.query.aid || '',
        teamId: this.$store.state.team.teamId || '',
        ...obj
      })
      return res
    }
  }
}
</script>

<style lang="scss" scoped="true">
  @import '~@/styles/variables.scss';

  .data {

    padding-bottom: 24px;
  }

  .trend-card {
    margin-bottom: 24px;
  }

  .table-box {
    .series-table {
      margin-top: 24px;
    }

    /deep/ .el-tabs__header{margin-bottom: 0;}
    /deep/ .el-tabs__content{
      padding-top: 24px;
    }

  }

  .left-box {

    .left-box-lt,
    .left-box-rt {
      display: flex;
      flex-wrap: nowrap;

      .el-select,
      .el-form-item__content,
      .el-input,
      .el-input__inner {
        max-width: 120px;

      }
    }

    .left-box-lt {
      margin-right: 40px;
    }

    .left-box-rt {
      .el-select {
        margin-right: 14px;
       ::v-deep .el-input:after{
          display: inline-block;
          content: '1';
          font-size: 0;
          position: absolute;
          top: 0;
          left: 0;
          height: 32px;
          width: 4px;

        }
      }

      .el-select::v-deep .el-input__inner {
        border-left-width: 4px;
      }

      .el-select:nth-of-type(1) ::v-deep .el-input:after{
        background-color: $chartColor1;
      }

      .el-select:nth-of-type(2) ::v-deep .el-input:after {
        background-color: $chartColor2;
      }

      .el-select:nth-of-type(3) ::v-deep .el-input:after {
        background-color: $chartColor3;
      }

      .el-select:nth-of-type(4) ::v-deep .el-input:after {
        background-color: $chartColor4;
      }

      .el-select:nth-of-type(5) ::v-deep .el-input:after {
        background-color: $chartColor5;
      }

    }

  }
</style>
